/**
 * Created by red on 2016/9/6.
 */
window.formatMoney = function (mVal, iAccuracy) {
    var fTmp = 0.00;//临时变量
    var iFra = 0;//小数部分
    var iInt = 0;//整数部分
    var aBuf = new Array(); //输出缓存
    var bPositive = true; //保存正负值标记(true:正数)
    /**
     * 输出定长字符串，不够补0
     * <li>闭包函数</li>
     * @param int iVal 值
     * @param int iLen 输出的长度
     */
    function funZero(iVal, iLen) {
        var sTmp = iVal.toString();
        var sBuf = new Array();
        for (var i = 0, iLoop = iLen - sTmp.length; i < iLoop; i++)
            sBuf.push('0');
        sBuf.push(sTmp);
        return sBuf.join('');
    };

    if (typeof(iAccuracy) === 'undefined')
        iAccuracy = 2;
    bPositive = (mVal >= 0);//取出正负号
    fTmp = (isNaN(fTmp = parseFloat(mVal))) ? 0 : Math.abs(fTmp);//强制转换为绝对值数浮点
    //所有内容用正数规则处理
    iInt = parseInt(fTmp); //分离整数部分
    iFra = parseInt((fTmp - iInt) * Math.pow(10, iAccuracy) + 0.5); //分离小数部分(四舍五入)

    do {
        aBuf.unshift(funZero(iInt % 1000, 3));
    } while ((iInt = parseInt(iInt / 1000)));
    aBuf[0] = parseInt(aBuf[0]).toString();//最高段区去掉前导0
    return ((bPositive) ? '' : '-') + aBuf.join(',') + '.' + ((0 === iFra) ? '00' : funZero(iFra, iAccuracy));
}

$(function () {
    $(".btn-buttom").each(function () {
        var o = $(this);
        if (o.hasClass("auto-url") && !$.isEmptyObject(o.attr("data-href"))) {
            o.click(function () {
                mui.openWindow({
                    createNew: true,
                    url: o.attr("data-href")
                })
            })
        }
    })
})
_Car = {
    /*购物车信息*/
    carInfo: {
        checkedPrice: 0.00,
        checkedCount: 0.00,
        totalCount: 0.00
    },

    _mask: null,

    mask: function () {
        if (_Car._mask == null) {
            _Car._mask = mui.createMask(function () {
                return true;
            })
        }
        return _Car._mask;
    },

    STORAGEKEY: {
        selectedEquip: "selectedEquip",
        selectedInvoice: "selectedInvoiceId",
        xjyyEquipSn: "xjyyEquipSn"
    },
    checkPermissionToBuy: function (pid) {

    },
    getLocalSelEquip: function () {
        return _Car.getLocalStorageItem(_Car.STORAGEKEY.selectedEquip);
    },

    getLocalSelInvoice: function () {
        return _Car.getLocalStorageItem(_Car.STORAGEKEY.selectedInvoice);
    },

    getLocalStorageItem: function (key) {
        if ($.isEmptyObject(key)) {
            return {};
        }
        var storageValue = localStorage.getItem(key);
        if (!$.isEmptyObject(storageValue)) {
            return $.parseJSON(storageValue);
        }
        return {};
    },

    link: {
        settle: "shoppingcar.do?goBuy"
    },

    msg: {
        addToCarSuc: function () {
            mui.toast("成功添加商品");
        }
    },

    openSimpleWindow: function (url, settings) {
        var setting = {url: url, createNew: true};
        if (!$.isEmptyObject(settings)) {
            $.extend(setting, settings);
        }
        mui.openWindow(setting);
    },

    init: function () {
        $.ajax({
            url: "shoppingcar.do?getCarInfo",
            async: false,
            dataType: "json",
            success: function (data) {
                data.totalPrice = Number(data.totalPrice).toFixed(2);
                data.checkedPrice = Number(data.checkedPrice).toFixed(2);
                _Car.carInfo = data;
            }
        })
    },

    updateCar: function (carInfo) {
        if (carInfo != undefined) {
            carInfo = $.type(carInfo) == 'string' ? $.parseJSON(carInfo) : carInfo;
            this.carInfo = carInfo;
        } else {
            _Car.init();
        }
    },

    /**
     * 获取购物车商品信息
     * @returns {_Car.carInfo|{}}
     */
    getCarInfo: function () {
        if ($.isEmptyObject(_Car.carInfo) || _Car.carInfo.totalCount == 0) {
            _Car.init();
        }
        return this.carInfo;
    },

    /**
     *
     * @param item {id:商品id,num:购买数量}
     * @param callback 回调函数
     */
    addItem: function (item, callback) {
        if ($.isEmptyObject(item)) {
            return;
        }
        $.ajax({
            url: "shoppingcar.do?addProduct",
            data: {partId: item.id, num: item.num},
            sync: false,
            dataType: 'json',
            success: function (data) {
                _Car.updateCar($.parseJSON(data));
                _Car.handleCallBack(callback);
                /*if (data.permission == 2) {
                    _Car.updateCar($.parseJSON(data));
                    _Car.handleCallBack(callback);
                } else {
                    var msg = '';
                    var redirectUrl = '';
                    switch (data.permission) {
                        case 0 :
                            msg = "您尚未注册，是否立即注册。";
                            redirectUrl = "loginWxController.do?goUserCreate";
                            break;
                        case 1:
                            msg = "您尚未进行认证，是否立即进行会员认证。";
                            redirectUrl = "loginWxController.do?goVipExplainWithCancel";
                            break;
                        case 3:
                            msg = "您的金牌会员认证正在审批中，请耐心等待！"
                            break;
                    }
                    mui.confirm(msg, '提示', function (e) {
                        if (e.index == 1) {
                            if (data.permission != 3) {
                                mui.createWindow()
                                _Car.openSimpleWindow(redirectUrl);
                                return;
                            }
                        }
                    })
                }*/
            }
        })
    },

    /**
     * 删除购买商品
     * @param item
     * @param callback
     */
    reduceItem: function (item, callback) {
        if (item != undefined) {
            $.post("shoppingcar.do?delCarItem", {partId: item.id, num: item.num}, function (data) {
                _Car.updateCar($.parseJSON(data));
                _Car.handleCallBack(callback);
            })
        }
    },

    handleCallBack: function (callback) {
        if ($.isFunction(callback)) {
            callback.call(_Car);
        }
    },

    itemCountChange: function (item, callback) {
        if (item != undefined) {
            $.post("shoppingcar.do?updateCarItem", {partId: item.id, num: item.num}, function (data) {
                _Car.updateCar($.parseJSON(data));
                _Car.handleCallBack(callback);
            })
        }
    },

    /**
     * 更新购物车汇总信息
     */
    updateCarSummaryInfo: function () {
        _Car.carInfo.checkedCount = 0;
        _Car.carInfo.checkedPrice = 0;
        $.each(_Car.getCarInfo().details, function (idx, itm) {
            if (itm.checkStatus == 1) {
                _Car.carInfo.checkedPrice += (itm.count * itm.price);
                _Car.carInfo.checkedCount += itm.count;
            }

        })
    },

    /**
     * 检查是否选中
     * @param itemId
     * @param checked
     */
    checkItem: function (itemId, checked) {
        if (!$.isEmptyObject(itemId)) {
            var id = itemId;
            $.each(_Car.getCarInfo().details, function (idx, itm) {
                if (itm.id == itemId) {
                    itm.checkStatus = (checked ? 1 : 0);
                }
            })
            _Car.updateCarSummaryInfo();
            $.post("shoppingcar.do?itemCheck", {itemId: id, checkStatus: (checked ? 1 : 0)}, function (data) {

            })
        }
    },

    /**
     * 获取购物车中已选商品
     * @returns {Array}
     */
    getSelectedProducts: function () {
        var items = new Array();
        $.each(_Car.getCarInfo().details, function (idx, itm) {
            if (itm.checkStatus == 1) {
                items.push(itm)
            }
        })
        return items;
    },

    genSelectPartByBp: function (bp, callback) {
        var result = {
            total: 0,
            count: 0,
            partClone: _Car.getSelectedProducts().slice(0)
        }
        if (result.partClone.length > 0) {
            $.getJSON("zyEquipmentSpareController.do?bpType", {bpNo: bp}, function (data) {
                if (!$.isEmptyObject(data)) {
                    $.each(result.partClone, function (idx, itm) {
                        if (itm.part.sort != 'fitting') {
                            itm.price = itm.part.cinemaPrice;
                        } else {
                            if (data.bpType == 'z') {
                                itm.price = itm.part.cfgcPrice;
                            } else if (data.bpType == 'h') {
                                itm.price = itm.part.hdPrice;
                            }
                        }
                        result.total += (itm.price * itm.count)
                        result.count += itm.count;
                    })
                } else {
                    result.count = _Car.getCarInfo().checkedCount;
                    result.total = _Car.getCarInfo().checkedPrice;
                }
                if (typeof callback == 'function') {
                    callback.call(_Car, result);
                }
            })
        }
    },

    /**
     * 获取已选商品的id
     * @returns {Array}
     */
    getSelectedProductIds: function () {
        var selItems = this.getSelectedProducts();
        var ids = new Array();
        if (!$.isEmptyObject(selItems)) {
            $.each(selItems, function (idx, itm) {
                ids.push(itm.id);
            })
        }
        return ids;
    },

    handleCheckAll: function () {
        $(".checkbox1").click(function () {
            if ($(":checked").not(".checkall").length != $(".checkbox1").not(":disabled").length) {
                $(".checkall").attr("checked", false);
            } else {
                $(".checkall").attr("checked", true);
            }
        })
    }

}
